﻿package com.sanli.test;


import java.awt.Component;
import java.awt.Cursor;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JTable;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JTableAutoResize.java
 *
 * Created on 2009-7-28, 20:54:35
 */
/**
 *
 * @author Administrator
 */
public class JTableAutoResize extends javax.swing.JFrame {

    /** Creates new form JTableAutoResize */
    public JTableAutoResize() {
        initComponents();
        addColumnResizeListener();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"张三", "山东省济南市趵突泉区", "吃饭睡觉打豆豆", "他不是一个好人，但是还不是太坏"},
                {"李四", "黑龙江省黑河", "吃饭睡觉打豆豆", "他不是一个好人，但是还不是太坏"},
                {"王二", "广东省深圳市福田区", "吃饭睡觉打豆豆", "他不是一个好人，但是还不是太坏"},
                {"小鱼", "火星-11区-223号-小黑屋", "吃饭睡觉打豆豆", "他不是一个好人，但是还不是太坏"}
            },
            new String [] {
                "姓名", "住址", "爱好", "评价"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, true, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 96, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new JTableAutoResize().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
    private JTableHeader tableHeader;

    /**
     * 添加列表自动调整的监听器，当双击表头不同列间的分隔线时，
     * 自动将分隔线左侧的列宽进行调整，使其内容可完全显示
     */
    private void addColumnResizeListener() {
        tableHeader = jTable1.getTableHeader();
        tableHeader.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {
                // 当光标处于两个列表间的分隔线上时，表头的光标呈东西调整的样式，通过
                // 鼠标的样式和点击次数来判断是否需要进行列宽调整
                int cursorType = tableHeader.getCursor().getType();
                if (cursorType == Cursor.E_RESIZE_CURSOR || cursorType == Cursor.W_RESIZE_CURSOR) {
                    if (e.getClickCount() == 2) {
                        // 获取光标点击位置的列号，这里将X的坐标减去3个像素,是为了保证取到的点始终是分隔线前的列号
                        int col = jTable1.getTableHeader().getColumnModel().getColumnIndexAtX(e.getX() - 3);
                        adjustColumnPreferredWidths(jTable1, col);
                    }
                }
            }
        });
    }

    /**
     * 根据给定的列号调整表格的列宽，此算法取自Swing hacker
     * @param table
     * @param col
     */
    public static void adjustColumnPreferredWidths(JTable table, int col) {
        // strategy - get max width for cells in column and
        // make that the preferred width
        TableColumnModel columnModel = table.getColumnModel();
        int maxwidth = 0;
        for (int row = 0; row < table.getRowCount(); row++) {
            TableCellRenderer rend =
                    table.getCellRenderer(row, col);
            Object value = table.getValueAt(row, col);
            Component comp =
                    rend.getTableCellRendererComponent(table,
                    value,
                    false,
                    false,
                    row,
                    col);
            maxwidth = Math.max(comp.getPreferredSize().width, maxwidth);
        } // for row
        TableColumn column = columnModel.getColumn(col);
        column.setPreferredWidth(maxwidth + 3);
    }
}
